<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Products - Anti-Drone Store</title>
    <meta name="description" content="Browse our complete collection of professional anti-drone equipment. Detection systems, jammers, command centers and accessories.">
    
    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    
    <!-- Common Styles -->
    <div th:replace="~{fragments/styles :: common-styles}"></div>
    <!-- Header Styles -->
    <div th:replace="~{fragments/header :: header-styles}"></div>
    
    <style>
        /* Page Header */
        .page-header {
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
            padding: 120px 0 80px;
            text-align: center;
            position: relative;
            overflow: hidden;
        }
        
        .page-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="rgba(30,58,138,0.1)" stroke-width="0.5"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
            opacity: 0.3;
        }
        
        .page-header-content {
            position: relative;
            z-index: 2;
        }
        
        .breadcrumb {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-bottom: 30px;
            font-size: 0.9rem;
        }
        
        .breadcrumb a {
            color: #64748b;
            text-decoration: none;
            transition: color 0.3s ease;
        }
        
        .breadcrumb a:hover {
            color: #1e3a8a;
        }
        
        .breadcrumb .current {
            color: #1e3a8a;
        }
        
        /* Filters */
        .filters-section {
            background: rgba(0, 0, 0, 0.02);
            padding: 30px 0;
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        }
        
        .filters-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 20px;
        }
        
        .filter-group {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .filter-label {
            color: #64748b;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.85rem;
            letter-spacing: 1px;
        }
        
        .filter-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .filter-btn {
            background: #ffffff;
            border: 1px solid rgba(0, 0, 0, 0.2);
            color: #64748b;
            padding: 8px 20px;
            border-radius: 25px;
            font-size: 0.85rem;
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 1px;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
        }
        
        .filter-btn:hover,
        .filter-btn.active {
            background: #1e3a8a;
            border-color: #1e3a8a;
            color: #fff;
            transform: translateY(-2px);
        }
        

        
        /* Products Grid */
        .products-grid {
            padding: 60px 0;
        }
        
        .products-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 30px;
        }
        
        .product-card {
            background: #ffffff;
            border: 1px solid rgba(0, 0, 0, 0.1);
            border-radius: 12px;
            overflow: hidden;
            transition: all 0.3s ease;
            height: 100%;
            display: flex;
            flex-direction: column;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .product-card:hover {
            transform: translateY(-10px);
            border-color: rgba(30, 58, 138, 0.3);
            box-shadow: 0 20px 40px rgba(30, 58, 138, 0.1);
        }
        
        .product-image {
            height: 220px;
            background: linear-gradient(135deg, #f1f5f9, #cbd5e1);
            display: flex;
            align-items: center;
            justify-content: center;
            color: #1e3a8a;
            font-size: 3rem;
            position: relative;
            overflow: hidden;
        }

        .product-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s ease;
        }

        .product-image:hover img {
            transform: scale(1.05);
        }

        .product-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s ease;
        }

        .fallback-icon {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #1e3a8a;
            font-size: 3rem;
        }

        .image-container {
            width: 100%;
            height: 100%;
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .image-loading {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #1e3a8a;
            font-size: 2rem;
            z-index: 1;
        }

        .product-img {
            opacity: 0;
            transition: opacity 0.3s ease, transform 0.3s ease;
        }

        .product-img.loaded {
            opacity: 1;
        }
        
        .product-image::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="8" height="8" patternUnits="userSpaceOnUse"><path d="M 8 0 L 0 0 0 8" fill="none" stroke="rgba(0,255,136,0.1)" stroke-width="0.5"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
            opacity: 0.3;
        }
        

        
        .product-content {
            padding: 20px;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
            min-height: 180px;
        }
        
        .product-category {
            color: #1e3a8a;
            font-size: 0.8rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 8px;
            opacity: 0.9;
        }
        
        .product-title {
            font-size: 1.1rem;
            font-weight: 600;
            margin-bottom: 12px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            line-height: 1.3;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
        }
        
        .product-description {
            color: #cccccc;
            margin-bottom: 25px;
            line-height: 1.6;
            flex-grow: 1;
            font-size: 0.95rem;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 4;
            -webkit-box-orient: vertical;
        }
        

        
        .product-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: auto;
            padding-top: 15px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .product-price {
            font-size: 1.2rem;
            font-weight: 600;
            color: #1e3a8a;
            opacity: 0.9;
        }
        
        .product-actions {
            display: flex;
            gap: 10px;
        }
        
        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 80px 20px;
            color: #666666;
        }
        
        .empty-state i {
            font-size: 4rem;
            margin-bottom: 20px;
            opacity: 0.5;
        }
        
        .empty-state h3 {
            margin-bottom: 15px;
            color: #cccccc;
        }
        
        /* Loading */
        .loading-state {
            text-align: center;
            padding: 80px 20px;
        }
        
        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 4px solid rgba(0, 255, 136, 0.3);
            border-top: 4px solid #1e3a8a;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .filters-container {
                flex-direction: column;
                align-items: stretch;
            }
            
            .filter-group {
                justify-content: center;
            }
            
            .filter-buttons {
                justify-content: center;
            }
            
            .products-container {
                grid-template-columns: 1fr;
                gap: 20px;
            }
            
            .product-footer {
                flex-direction: column;
                gap: 15px;
                align-items: stretch;
            }
            
            .product-actions {
                justify-content: center;
            }
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div th:replace="~{fragments/header :: header}"></div>

    <!-- Page Header -->
    <section class="page-header">
        <div class="container">
            <div class="page-header-content">
                <nav class="breadcrumb">
                    <a href="/" th:href="@{/}">Home</a>
                    <span>/</span>
                    <span class="current">Products</span>
                </nav>
                <h1>ANTI-DRONE <span class="highlight">EQUIPMENT</span></h1>
                <p class="section-subtitle">Professional counter-UAV systems for every security need</p>
            </div>
        </div>
    </section>

    <!-- Filters -->
    <section class="filters-section">
        <div class="container">
            <div class="filters-container">
                <div class="filter-group">
                    <span class="filter-label">Category:</span>
                    <div class="filter-buttons" id="categoryFilters">
                        <a href="#" class="filter-btn active" data-category-id="" data-category="all">All Products</a>
                        <!-- 动态加载的分类按钮将插入到这里 -->
                    </div>
                </div>
                

            </div>
        </div>
    </section>

    <!-- Products Grid -->
    <section class="products-grid">
        <div class="container">
            <!-- Loading State -->
            <div class="loading-state" id="loadingState" style="display: none;">
                <div class="loading-spinner"></div>
                <p>Loading products...</p>
            </div>
            
            <!-- Products Container -->
            <div class="products-container" id="productsContainer">
                <!-- 动态加载的产品将插入到这里 -->
            </div>
            
            <!-- Empty State -->
            <div class="empty-state" id="emptyState" style="display: none;">
                <i class="fas fa-search"></i>
                <h3>No Products Found</h3>
                <p>Try adjusting your filters or search criteria</p>
                <a href="#" class="btn btn-primary" onclick="clearFilters()">Clear Filters</a>
            </div>
        </div>
    </section>

    <!-- Footer -->
    <div th:replace="~{fragments/footer :: footer}"></div>

    <!-- Header Scripts -->
    <div th:replace="~{fragments/header :: header-scripts}"></div>
    
    <script>
        // Product filtering and sorting
        document.addEventListener('DOMContentLoaded', function() {
            const categoryFilters = document.getElementById('categoryFilters');
            const productsContainer = document.getElementById('productsContainer');
            const emptyState = document.getElementById('emptyState');
            const loadingState = document.getElementById('loadingState');

            let currentCategoryId = '';
            let categories = [];
            let products = [];
            let filteredProducts = [];

            // 初始化页面
            initializePage();

            // 监听语言切换事件
            setupLanguageChangeListener();

            /**
             * 设置语言切换监听器
             */
            function setupLanguageChangeListener() {
                // 保存当前语言ID
                let currentLanguageId = localStorage.getItem('selectedLanguage') || '1';

                // 定期检查语言是否发生变化
                setInterval(() => {
                    const newLanguageId = localStorage.getItem('selectedLanguage') || '1';
                    if (newLanguageId !== currentLanguageId) {
                        currentLanguageId = newLanguageId;
                        console.log('语言已切换到:', newLanguageId);
                        // 重新加载数据
                        initializePage();
                    }
                }, 500); // 每500ms检查一次

                // 也可以监听storage事件（当其他标签页修改localStorage时触发）
                window.addEventListener('storage', function(e) {
                    if (e.key === 'selectedLanguage' && e.newValue !== currentLanguageId) {
                        currentLanguageId = e.newValue || '1';
                        console.log('语言已切换到:', currentLanguageId);
                        initializePage();
                    }
                });
            }

            /**
             * 初始化页面
             */
            function initializePage() {
                showLoading();
                // 并行加载分类和产品数据
                Promise.all([
                    loadCategories(),
                    loadProducts()
                ]).then(() => {
                    hideLoading();
                    bindEvents();
                    filterProducts();
                }).catch(error => {
                    console.error('初始化页面失败:', error);
                    hideLoading();
                    showErrorState(error.message || '加载数据失败，请刷新页面重试');
                });
            }

            /**
             * 加载商品分类
             */
            function loadCategories() {
                const languageId = localStorage.getItem('selectedLanguage') || '1';
                console.log('加载分类，当前语言ID:', languageId);
                return fetch(`/api/classify/list?languageId=${languageId}`)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                        }
                        return response.json();
                    })
                    .then(data => {
                        console.log('分类API响应:', data);
                        if (data.code === 200 && data.data) {
                            categories = data.data;
                            renderCategories();
                        } else {
                            console.error('加载分类失败:', data.message);
                            throw new Error(data.message || '加载分类失败');
                        }
                    })
                    .catch(error => {
                        console.error('分类API请求失败:', error);
                        throw error;
                    });
            }

            /**
             * 加载商品列表
             */
            function loadProducts() {
                const languageId = localStorage.getItem('selectedLanguage') || '1';
                console.log('加载商品，当前语言ID:', languageId);
                return fetch(`/api/product/list?languageId=${languageId}`)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                        }
                        return response.json();
                    })
                    .then(data => {
                        console.log('商品API响应:', data);
                        if (data.code === 200 && data.data) {
                            products = data.data;
                        } else {
                            console.error('加载产品失败:', data.message);
                            throw new Error(data.message || '加载产品失败');
                        }
                    })
                    .catch(error => {
                        console.error('商品API请求失败:', error);
                        throw error;
                    });
            }

            /**
             * 渲染分类按钮
             */
            function renderCategories() {
                // 保留"All Products"按钮
                const allBtn = categoryFilters.querySelector('[data-category="all"]');
                categoryFilters.innerHTML = '';
                categoryFilters.appendChild(allBtn);

                // 添加动态分类
                categories.forEach(category => {
                    const btn = document.createElement('a');
                    btn.href = '#';
                    btn.className = 'filter-btn';
                    btn.setAttribute('data-category-id', category.id);
                    btn.setAttribute('data-category', category.classifyName);
                    btn.textContent = category.classifyName;
                    categoryFilters.appendChild(btn);
                });
            }

            /**
             * 绑定事件监听器
             */
            function bindEvents() {
                // 分类筛选事件
                categoryFilters.addEventListener('click', function(e) {
                    if (e.target.classList.contains('filter-btn')) {
                        e.preventDefault();

                        // 更新活动状态
                        categoryFilters.querySelectorAll('.filter-btn').forEach(btn => {
                            btn.classList.remove('active');
                        });
                        e.target.classList.add('active');

                        // 更新当前分类
                        currentCategoryId = e.target.getAttribute('data-category-id') || '';

                        // 重新筛选
                        filterProducts();
                    }
                });
            }

            /**
             * 筛选产品
             */
            function filterProducts() {
                showLoading();

                setTimeout(() => {
                    // 筛选产品
                    if (currentCategoryId === '') {
                        filteredProducts = [...products];
                    } else {
                        filteredProducts = products.filter(product =>
                            product.classifyId && product.classifyId.toString() === currentCategoryId.toString()
                        );
                    }

                    // 渲染产品
                    renderProducts();
                    hideLoading();
                }, 300);
            }

            /**
             * 渲染产品列表
             */
            function renderProducts() {
                productsContainer.innerHTML = '';

                if (filteredProducts.length === 0) {
                    showEmptyState();
                    return;
                }

                hideEmptyState();

                filteredProducts.forEach((product, index) => {
                    const productCard = createProductCard(product, index);
                    productsContainer.appendChild(productCard);
                });
            }

            /**
             * 创建产品卡片
             */
            function createProductCard(product, index) {
                const card = document.createElement('div');
                card.className = 'product-card';
                card.setAttribute('data-category-id', product.classifyId || '');
                card.setAttribute('data-product-id', product.id || '0');

                // 获取分类名称 - 优先使用ProductVo中的classifyName
                const categoryName = product.classifyName || 'Unknown Category';

                // 由于ProductVo没有price字段，显示联系询价
                const price = 'Contact for Price';

                // 根据分类选择图标
                const getIconByCategory = (categoryName) => {
                    const name = categoryName.toLowerCase();
                    if (name.includes('detection') || name.includes('radar') || name.includes('sensor')) {
                        return 'fa-radar';
                    } else if (name.includes('jammer') || name.includes('neutralization') || name.includes('jamming')) {
                        return 'fa-broadcast-tower';
                    } else if (name.includes('control') || name.includes('command') || name.includes('system')) {
                        return 'fa-desktop';
                    } else if (name.includes('accessory') || name.includes('antenna') || name.includes('kit')) {
                        return 'fa-satellite';
                    } else {
                        return 'fa-cube';
                    }
                };

                const iconClass = getIconByCategory(categoryName);

                // 不再显示特性列表，因为ProductVo中没有相关字段

                // 获取产品图片HTML
                const getProductImageHtml = (product) => {
                    // 调试日志：查看产品完整数据结构
                    console.log('产品数据结构:', product);

                    // 检查是否有图片列表
                    if (product.images && product.images.length > 0) {
                        const firstImage = product.images[0];
                        if (firstImage.imagePath) {
                            const imageUrl = `/api/file/get?filename=${firstImage.imagePath}`;
                            return `<div class="image-container">
                                        <img src="${imageUrl}"
                                             alt="${product.productName || 'Product Image'}"
                                             class="product-img"
                                             loading="lazy"
                                             onload="handleImageLoad(this)"
                                             onerror="handleImageError(this, '${iconClass}')">
                                        <div class="fallback-icon" style="display: none;">
                                            <i class="fas ${iconClass}"></i>
                                        </div>
                                        <div class="image-loading" style="display: flex;">
                                            <i class="fas fa-spinner fa-spin"></i>
                                        </div>
                                    </div>`;
                        }
                    }

                    // 检查是否有产品封面
                    if (product.productImage) {
                        const imageUrl = `/api/file/get?filename=${product.productImage}`;
                        return `<div class="image-container">
                                    <img src="${imageUrl}"
                                         alt="${product.productName || 'Product Image'}"
                                         class="product-img"
                                         loading="lazy"
                                         onload="handleImageLoad(this)"
                                         onerror="handleImageError(this, '${iconClass}')">
                                    <div class="fallback-icon" style="display: none;">
                                        <i class="fas ${iconClass}"></i>
                                    </div>
                                    <div class="image-loading" style="display: flex;">
                                        <i class="fas fa-spinner fa-spin"></i>
                                    </div>
                                </div>`;
                    }

                    // 没有图片时显示图标
                    return `<div class="fallback-icon"><i class="fas ${iconClass}"></i></div>`;
                };

                card.innerHTML = `
                    <div class="product-image">
                        ${getProductImageHtml(product)}
                    </div>
                    <div class="product-content">
                        <div class="product-category">${categoryName}</div>
                        <h3 class="product-title">${product.productName || 'Unknown Product'}</h3>
                        <p class="product-description">${product.productInfo || 'No description available.'}</p>
                        <div class="product-footer">
                            <div class="product-price">${price}</div>
                            <div class="product-actions">
                                <a href="/product/${product.id}" class="btn btn-primary btn-sm">VIEW DETAILS</a>
                            </div>
                        </div>
                    </div>
                `;

                // 添加动画延迟
                card.style.opacity = '0';
                card.style.transform = 'translateY(30px)';
                card.style.transition = 'all 0.6s ease';

                setTimeout(() => {
                    card.style.opacity = '1';
                    card.style.transform = 'translateY(0)';
                }, 100 + (index * 100));

                return card;
            }

            /**
             * 显示加载状态
             */
            function showLoading() {
                loadingState.style.display = 'block';
                productsContainer.style.opacity = '0.5';
                hideEmptyState();
            }

            /**
             * 隐藏加载状态
             */
            function hideLoading() {
                loadingState.style.display = 'none';
                productsContainer.style.opacity = '1';
            }

            /**
             * 显示空状态
             */
            function showEmptyState() {
                emptyState.style.display = 'block';
                productsContainer.innerHTML = '';
            }

            /**
             * 隐藏空状态
             */
            function hideEmptyState() {
                emptyState.style.display = 'none';
            }

            /**
             * 显示错误状态
             */
            function showErrorState(message) {
                productsContainer.innerHTML = `
                    <div style="text-align: center; padding: 80px 20px; color: #ff4444;">
                        <i class="fas fa-exclamation-triangle" style="font-size: 4rem; margin-bottom: 20px; opacity: 0.5;"></i>
                        <h3 style="margin-bottom: 15px; color: #cccccc;">加载失败</h3>
                        <p style="margin-bottom: 20px;">${message}</p>
                        <button onclick="location.reload()" class="btn btn-primary">重新加载</button>
                    </div>
                `;
                hideEmptyState();
            }
        });

        // 图片加载错误处理函数（全局函数）
        window.handleImageError = function(img, iconClass) {
            console.log('图片加载失败:', img.src);
            img.style.display = 'none';

            // 隐藏加载状态
            const container = img.closest('.image-container');
            if (container) {
                const loadingIcon = container.querySelector('.image-loading');
                if (loadingIcon) {
                    loadingIcon.style.display = 'none';
                }

                // 显示备用图标
                const fallbackIcon = container.querySelector('.fallback-icon');
                if (fallbackIcon) {
                    fallbackIcon.style.display = 'flex';
                    const icon = fallbackIcon.querySelector('i');
                    if (icon) {
                        icon.className = `fas ${iconClass}`;
                    }
                }
            }
        };

        // 图片加载成功处理函数（全局函数）
        window.handleImageLoad = function(img) {
            img.classList.add('loaded');

            // 隐藏加载状态
            const container = img.closest('.image-container');
            if (container) {
                const loadingIcon = container.querySelector('.image-loading');
                if (loadingIcon) {
                    loadingIcon.style.display = 'none';
                }
            }
        };

        // Clear filters function (全局函数，供HTML调用)
        window.clearFilters = function() {
            const allBtn = document.querySelector('.filter-btn[data-category="all"]');
            if (allBtn) {
                allBtn.click();
            }
        }
        
        // Smooth scrolling
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function (e) {
                e.preventDefault();
                const target = document.querySelector(this.getAttribute('href'));
                if (target) {
                    target.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            });
        });
    </script>
</body>
</html>
